package beans;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.bind.JAXBElement;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import javax.xml.ws.WebServiceRef;

import pr.PurchaseRequisitionBPEL;
import pr.Purchaserequisitionbpel_client_ep;

import pr.types.ConfigurationType;
import pr.types.ItemDetailsType;
import pr.types.ObjectFactory;
import pr.types.ProcessResponse;
import pr.types.PurchaseRequisitionHeaderType;

import pr.types.PurchaseRequisitionType;

import utils.ADFUtil;
import utils.JSFUtil;
import utils.MessageUtils;

public class BackingBean {
    private List<PurchaseRequisition> purchaseReq;
    private int purchaseCount=0;
    private List<Configuration> configList;
    private PurchaseRequisition pr ;
    
    @WebServiceRef
    Purchaserequisitionbpel_client_ep prc = new Purchaserequisitionbpel_client_ep();
    
    public BackingBean() {
        
        pr =  new PurchaseRequisition();
        TestBean test = new TestBean();
        purchaseReq = new ArrayList<PurchaseRequisition>();
        purchaseReq.add(pr);
        purchaseCount++;
    }
   


    public void setPurchaseReq(List<PurchaseRequisition> purchaseReq) {
        this.purchaseReq = purchaseReq;
    }

    public List<PurchaseRequisition> getPurchaseReq() {
        return purchaseReq;
    }

    public void setPurchaseCount(int purchaseCount) {
        this.purchaseCount = purchaseCount;
    }

    public int getPurchaseCount() {
        return purchaseCount;
    }
    public String addConfig() {
        Object uuid =
            ADFUtil.resolveExpression("#{pageFlowScope.pRequestAdd}");
        Configuration configObject = new Configuration();
        configObject.setParentUuid(uuid.toString());
        for(PurchaseRequisition p : purchaseReq){
            if(uuid.equals(p.getUuid())){
                p.getConfig().add(configObject);
                p.setConfigCount(p.getConfigCount()+1);
            }
        }
       
        return null;
    }
    
    public String deleteConfig() {
        Object parentUuid =
            ADFUtil.resolveExpression("#{pageFlowScope.pParentRemove}");
        Object uuid =
            ADFUtil.resolveExpression("#{pageFlowScope.pConfigRemove}");
        if (parentUuid != null) {
            
                for (PurchaseRequisition p : purchaseReq) {
                    if (parentUuid.equals(p.getUuid())) {
                        for(Configuration c :p.getConfig()){
                            if(c.getUuid().equals(uuid)){
                                p.getConfig().remove(c);
                                return null;
                            }
                        }
                        
                        return null;
                    }
              
            }
        }
        return null;
    }

    public String deleteRequest() {
        Object uuid =
            ADFUtil.resolveExpression("#{pageFlowScope.pRequestRemove}");
        if (uuid != null) {
         
                for (PurchaseRequisition pr : purchaseReq) {
                    if (uuid.equals(pr.getUuid())) {
                        purchaseReq.remove(pr);
                        return null;
                    }
                }
           
        }
        return null;
    }

    public String addRequest() {
    
        PurchaseRequisition pr = new PurchaseRequisition();
        purchaseReq.add(pr);
        purchaseCount++;
        return null;
    }

    public void setConfigList(List<Configuration> configList) {
        this.configList = configList;
    }

    public List<Configuration> getConfigList() {
        Object uuid =
            ADFUtil.resolveExpression("#{requestScope.pRequestRemove}");
        System.out.println("PageFlow-UUID =" +uuid.toString());
        List<Configuration> list = new ArrayList<Configuration>();
        for(PurchaseRequisition c : purchaseReq) {
            System.out.println("List UUID ="+ c.getUuid());
            if (uuid.equals(c.getUuid())) {
                list = c.getConfig();
            }
        }
      return list;
    }
    public XMLGregorianCalendar returnDate(String dateString) throws ParseException,
                                                    DatatypeConfigurationException {
        Date date=null;
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        date=df.parse( dateString );
        GregorianCalendar cal1 = new GregorianCalendar();
        cal1.setTime(date);
        
        XMLGregorianCalendar xmlDate2 = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH)+1, cal1.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
        return xmlDate2;
    }

    public String saveToService() throws ParseException,
                                         DatatypeConfigurationException {
        // List<PurchaseRequisitionType> purchaseList = new ArrayList<PurchaseRequisitionType>();

        int i = 1;
        pr.types.PurchaseRequisition prRequest =
            new pr.types.PurchaseRequisition();
        for (PurchaseRequisition p : purchaseReq) {
            PurchaseRequisitionHeaderType purchaseHeaderType =
                new PurchaseRequisitionHeaderType();

            purchaseHeaderType.setApprovedBy(p.getApprovedBy());
            DateFormat formatter =
                new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = (Date)formatter.parse(p.getDateField().toString());
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);
            String formatedDate1 =
                cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) +
                                                 1) + "-" +
                cal1.get(Calendar.DATE);
            XMLGregorianCalendar xmlDate = returnDate(formatedDate1);
            purchaseHeaderType.setDate(xmlDate);
            purchaseHeaderType.setPRNo(p.getPRNo());
            purchaseHeaderType.setRequestedTo(p.getRequestedTo());
            purchaseHeaderType.setRequestedby(p.getRequestedBy());


            ItemDetailsType itemType = new ItemDetailsType();
            itemType.setAdditionalRequirement(p.getAdditionalRequirement());
            itemType.setItemType(p.getItemType());
            itemType.setManufacture(p.getManufacture());
            itemType.setModelNumber(p.getModelNumber());
            itemType.setQuantity(p.getQuantity());
            itemType.setRemarks(p.getRemarks());


            for (Configuration c : p.getConfig()) {
                ConfigurationType configType = new ConfigurationType();
                configType.setConfigurationModel(c.getConfigurationModel());
                configType.setConfigurationType(c.getConfigurationType());
                System.out.println("Model: " + c.getConfigurationModel());
                System.out.println("Type: " + c.getConfigurationType());
                itemType.getConfiguration().add(configType);
            }


            PurchaseRequisitionType purchaseType =
                new PurchaseRequisitionType();
            purchaseType.setCreatedBy(p.getCreatedBy());
            formatter = new SimpleDateFormat("yyyy-MM-dd");
            date1 = (Date)formatter.parse(p.getCreatedDate().toString());
            cal1 = Calendar.getInstance();
            cal1.setTime(date1);
            formatedDate1 =
                    cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH) +
                                                     1) + "-" +
                    cal1.get(Calendar.DATE);
            xmlDate = returnDate(formatedDate1);
            ObjectFactory oc = new ObjectFactory();
            JAXBElement<XMLGregorianCalendar> xmlD =
                oc.createPurchaseRequisitionTypeCreatedDate(xmlDate);
            purchaseType.setCreatedDate(xmlD);
            purchaseType.setItemDetails(itemType);
            purchaseType.setPurchaseRequisitionHeader(purchaseHeaderType);


            prRequest.getPurchaseRequisitionDetails().add(purchaseType);


            System.out.println("Request " + i);
            i++;
            System.out.println("-----------");
            System.out.println("Additional Requirement: " +
                               p.getAdditionalRequirement());
            System.out.println("Approved By: " + p.getApprovedBy());
            System.out.println("Created By: " + p.getCreatedBy());
            System.out.println("Created Date: " + p.getCreatedDate());
            System.out.println("Date: " + p.getDateField());
            System.out.println("Item Type: " + p.getItemType());
            System.out.println("Requested To: " + p.getRequestedTo());
            System.out.println("Requested By: " + p.getRequestedBy());
            System.out.println("Remarks: " + p.getRemarks());
            System.out.println("Quantity: " + p.getQuantity());
            System.out.println("PRNo: " + p.getPRNo());
            System.out.println("Model Number: " + p.getModelNumber());
            System.out.println("Manufacturer : " + p.getManufacture());
            int j = 1;
            for (Configuration c : p.getConfig()) {
                System.out.println("Configuration " + j);
                j++;
                System.out.println("------------");
                System.out.println("Model: " + c.getConfigurationModel());
                System.out.println("Type: " + c.getConfigurationType());
                ;
            }
        }

        PurchaseRequisitionBPEL prBpel = prc.getPurchaseRequisitionBPEL_pt();
        ProcessResponse response = prBpel.process(prRequest);
        response.getResult();
        System.out.println("response :" + response.getResult());
        if(response.getResult().equals("Data Inserted Successfully")){
            MessageUtils.displayMessage(null, "Save Successful");
        }else{
            MessageUtils.displayErrorMessage(null, "Unsuccessful operation due to SOA internal error. Please try after sometime. Sorry for the inconvenience");
        }

        return null;
    
}
}
